package com.moss.cloud.auth.biz.config;

import com.moss.cloud.auth.biz.expand.miniapp.MiniAppAuthenticationProvider;
import com.moss.cloud.auth.biz.expand.mobile.SmsCodeAuthenticationProvider;
import com.moss.cloud.auth.biz.service.ISysUserService;
import com.moss.cloud.common.security.component.RedisTemplateOps;
import com.moss.cloud.remote.api.rpc.RemoteRpcService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.Collections;

/**
 * WebSecurity配置
 * @author 瑾年
 * @date 2023年3月5日
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    private final UserDetailsService userDetailsService;
    private final RedisTemplateOps redisTemplateOps;
    private final RemoteRpcService remoteRpcService;
    private final ISysUserService sysUserService;

    public WebSecurityConfiguration(UserDetailsService userDetailsService, RedisTemplateOps redisTemplateOps, RemoteRpcService remoteRpcService, ISysUserService sysUserService) {
        this.userDetailsService = userDetailsService;
        this.redisTemplateOps = redisTemplateOps;
        this.remoteRpcService = remoteRpcService;
        this.sysUserService = sysUserService;
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin().permitAll()
                .and().cors().configurationSource(corsConfigurationSource());
    }
    /**
     * 注入自定义的userDetailsService实现，获取用户信息，设置密码加密方式
     *
     * @param authenticationManagerBuilder
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder
                .authenticationProvider(smsCodeAuthenticationProvider())
                .authenticationProvider(miniAppAuthenticationProvider())
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());
    }
    /**
     * 屏蔽security的拦截功能，类似于白名单，但是经过网关也会鉴权
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/actuator/*","/auth/auth/logout",
                "/auth/captcha/*","/auth/auth/smsCode","/auth/auth/authFail");
    }

    /**
     * 手机验证码认证授权提供者
     *
     * @return
     */
    @Bean
    public SmsCodeAuthenticationProvider smsCodeAuthenticationProvider() {
        SmsCodeAuthenticationProvider provider = new SmsCodeAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService);
        provider.setRedisTemplateOps(redisTemplateOps);
        return provider;
    }
    /**
     * 微信小程序认证授权提供者
     *
     * @return
     */
    @Bean
    public MiniAppAuthenticationProvider miniAppAuthenticationProvider() {
        MiniAppAuthenticationProvider provider = new MiniAppAuthenticationProvider();
        provider.setRemoteRpcService(remoteRpcService);
        provider.setSysUserService(sysUserService);
        provider.setUserDetailsService(userDetailsService);
        return provider;
    }


    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource(){
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedHeaders(Collections.singletonList("*"));
        corsConfiguration.setAllowedMethods(Collections.singletonList("*"));
        corsConfiguration.setAllowedOrigins(Collections.singletonList("*"));
        corsConfiguration.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",corsConfiguration);
        return source;
    }

}
